<template xmlns:v-sortable="http://www.w3.org/1999/xhtml">
  <ul class="treelist" v-sortable:treeview="sortableOptions">
    <li :class="{'parent': root.children.length}" :data-id="root.id" v-for="root in treenodes" type="root">
      <span class="treeitem" @click.stop="active(root)">
        <i v-if="root.icon" :class="root.icon"></i>
        <span class="mr-2">{{root.name}}</span>
        <span class="mr-auto text-muted">{{root.code}}</span>
        <span class="indicator" @click.stop="toggle"></span>
      </span>
      <children v-if="root.children.length" :parent="root"></children>
    </li>
  </ul>
</template>
<!--
  权限树形列表
-->
<script>
  import {dispatch} from '../../misc/emitter'
  import {closest} from '../../misc/utils'

  function _active (e) {
    var parent = closest(e.currentTarget, 'ul.treelist')
    parent.querySelectorAll('.treeitem').forEach(c => {
      c.classList.remove('active')
    })
    e.currentTarget.classList.add('active')
  }

  var sortableOptions = {
    animation: 150,
    onMove (e, original) { // when item moves in the list or between lists, return false for cancel
      return e.related.parentNode === e.dragged.parentNode
    }
  }

  /* 展开/收缩子元素 */
  function toggle (e) {
    e.currentTarget.parentNode.parentNode.classList.toggle('open')
  }

  function active (item) {
    dispatch.call(this, 'treeview', 'active', item)
  }

  export default {
    name: 'treeview',
    props: ['treenodes'],
    data: () => ({sortableOptions}),
    methods: {active, toggle},
    components: {
      children: {
        name: 'children',
        props: ['parent', 'checked'],
        data: () => ({sortableOptions}),
        template: `<ul v-sortable:treeview="sortableOptions">
          <li :class="{'parent': child.children.length}" :data-id="child.id" v-for="child in parent.children">
            <span class="treeitem" @click.stop="active(child)">
              <i v-if="child.icon" :class="child.icon"></i>
              <span class="mr-2">{{child.name}}</span>
              <span class="mr-auto text-muted">{{child.code}}</span>
              <span class="indicator" @click.stop="toggle"></span>
            </span>
            <children v-if="child.children.length" :parent="child"></children>
          </li>
        </ul>`,
        methods: {active, toggle}
      }
    }
  }
</script>

<style>
  .treeitem.active {
    background: #efefef;
    box-shadow: 0 1px 15px 0 rgba(0, 0, 0, 0.2)
  }
</style>